/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.mes.base.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.mes.base.entity.DictTreeNode;
import org.springblade.modules.mes.base.entity.MaterialGroup;
import org.springblade.modules.mes.base.entity.MaterialInfo;
import org.springblade.modules.mes.base.service.IMaterialGroupService;
import org.springblade.modules.mes.base.service.IMaterialInfoService;
import org.springblade.modules.mes.base.vo.MaterialGroupVO;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 材料组 控制器
 *
 * @author BladeX
 * @since 2020-09-11
 */
@RestController
@AllArgsConstructor
@RequestMapping("/materialgroup")
@Api(value = "材料组", tags = "材料组接口")
public class MaterialGroupController extends BladeController {

	private final IMaterialGroupService materialGroupService;
	private IMaterialInfoService materialInfoService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	//@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入materialGroup")
	public R<MaterialGroup> detail(MaterialGroup materialGroup) {
		MaterialGroup detail = materialGroupService.getOne(Condition.getQueryWrapper(materialGroup));
		return R.data(detail);
	}

	/**
	 * 不分页 材料组
	 */
	@GetMapping("/list")
	//@ApiOperationSupport(order = 2)
	@ApiOperation(value = "不分页", notes = "传入materialGroup")
	public R<List<MaterialGroupVO>> list(MaterialGroupVO materialGroupVO, Query query) {
		List<MaterialGroupVO> materialGroupVOList = materialGroupService.getMaterialGroupVOList(materialGroupVO);
		return R.data(materialGroupVOList);
	}

	/**
	 * 分页 材料组
	 */
	@GetMapping("/pagelist")
	//@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入materialGroup")
	public R<IPage<MaterialGroup>> pageList(MaterialGroup materialGroup, Query query) {
		IPage<MaterialGroup> pages = materialGroupService.page(Condition.getPage(query), Condition.getQueryWrapper(materialGroup));
		return R.data(pages);
	}

	/**
	 * 自定义分页 材料组
	 */
	@GetMapping("/page")
	//@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入materialGroup")
	public R<IPage<MaterialGroupVO>> page(MaterialGroupVO materialGroup, Query query) {
		IPage<MaterialGroupVO> pages = materialGroupService.selectMaterialGroupPage(Condition.getPage(query), materialGroup);
		return R.data(pages);
	}

	/**
	 * 新增 材料组
	 */
	@PostMapping("/save")
	//@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入materialGroup")
	public R save(@Valid @RequestBody MaterialGroup materialGroup) {
		QueryWrapper queryWrapper = new QueryWrapper<MaterialGroup>().eq("material_type",materialGroup.getMaterialType())
			.eq("material_group_no", materialGroup.getMaterialGroupNo());
		long count = materialGroupService.count(queryWrapper);
		if(count > 0){
			return R.fail("物料组编码已存在，请重新编辑！");
		}
		long nameCount = materialGroupService.count(new QueryWrapper<MaterialGroup>().eq("material_type",materialGroup.getMaterialType())
			.eq("material_group_name", materialGroup.getMaterialGroupName()));
		if (nameCount>0){
			return R.fail("物料组名称已存在，请重新编辑！");
		}
		boolean flag = materialGroupService.save(materialGroup);
		/**异步向物流推送材料组信息-新增 start**/
		/*if(flag){
			ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
			MaterialGroupSyncThread thread = new MaterialGroupSyncThread(1,materialGroup,null);
			cachedThreadPool.execute(thread);
		}*/
		/**异步向物流推送材料组信息-新增 end**/
		return R.status(flag);
	}

	/**
	 * 修改 材料组
	 */
	@PostMapping("/update")
	//@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入materialGroup")
	public R update(@Valid @RequestBody MaterialGroup materialGroup) {
		QueryWrapper queryWrapper = new QueryWrapper<MaterialGroup>().ne("id", materialGroup.getId()).eq("material_type",materialGroup.getMaterialType())
			.eq("material_group_no", materialGroup.getMaterialGroupNo());
		long count = materialGroupService.count(queryWrapper);
		if(count > 0){
			return R.fail("物料组编码已存在，请重新编辑！");
		}
		QueryWrapper queryWrapperName = new QueryWrapper<MaterialGroup>().ne("id", materialGroup.getId()).eq("material_type",materialGroup.getMaterialType())
			.eq("material_group_name", materialGroup.getMaterialGroupName());
		long nameCount = materialGroupService.count(queryWrapperName);
		if(nameCount > 0){
			return R.fail("物料组名称已存在，请重新编辑！");
		}

		MaterialGroup mg = materialGroupService.getById(materialGroup.getId());
		if (!mg.getMaterialType().equals(materialGroup.getMaterialType()) || !mg.getMaterialGroupNo().equals(materialGroup.getMaterialGroupNo())){
			long materialCounts = materialInfoService.count(new QueryWrapper<MaterialInfo>().eq("material_type",mg.getMaterialType()).eq("material_group_no",mg.getMaterialGroupNo()));
			if (materialCounts>0){
				return R.fail("该物料组已被引用，不能进行修改！");
			}
		}
		boolean flag = materialGroupService.updateById(materialGroup);
		/**异步向物流推送材料组信息-新增 start**/
		/*if(flag){
			ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
			MaterialGroupSyncThread thread = new MaterialGroupSyncThread(2,materialGroup,null);
			cachedThreadPool.execute(thread);
		}*/
		/**异步向物流推送材料组信息-新增 end**/
		return R.status(flag);
	}

//	/**
//	 * 新增或修改 材料组
//	 */
//	@PostMapping("/submit")
//	//@ApiOperationSupport(order = 6)
//	@ApiOperation(value = "新增或修改", notes = "传入materialGroup")
//	public R submit(@Valid @RequestBody MaterialGroup materialGroup) {
//		QueryWrapper queryWrapper = new QueryWrapper<MaterialGroup>().ne("id", materialGroup.getId())
//				.and(wapper -> wapper.eq("number", materialGroup.getNumber()).or().eq("name", materialGroup.getName()));
//		int count = materialGroupService.count(queryWrapper);
//		if(count > 0){
//			return R.fail("材料组编码或名称已存在，请重新编辑！");
//		}
//		return R.status(materialGroupService.saveOrUpdate(materialGroup));
//	}


	/**
	 * 删除 材料组
	 */
	@PostMapping("/remove")
	//@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		List<Long> idList = Func.toLongList(ids);
		List<MaterialGroup> materialGroupList = materialGroupService.listByIds(idList);
		List<String> groupNoList = materialGroupList.stream().map(MaterialGroup::getMaterialGroupNo).distinct().collect(Collectors.toList());
		List<MaterialInfo> mList = materialInfoService.list(new QueryWrapper<MaterialInfo>().lambda().in(MaterialInfo::getMaterialGroupNo, groupNoList));
		for (MaterialGroup materialGroup : materialGroupList) {
			List<MaterialInfo> curMList = mList.stream().filter(x -> x.getMaterialGroupNo().equals(materialGroup.getMaterialGroupNo())).collect(Collectors.toList());
			if(CollectionUtil.isNotEmpty(curMList)){
				List<String> curMNoList = curMList.stream().map(MaterialInfo::getMaterialNo).collect(Collectors.toList());
				String join = String.join(",", curMNoList);
				String msg = String.format("物料组:%s,被物料引用,不能删除.物料:%s", materialGroup.getMaterialGroupNo(), join);
				return R.fail(msg);
			}
		}
		boolean flag = materialGroupService.deleteLogic(idList);
		/**异步向物流推送材料组信息-新增 start**/
		/*if(flag){
			ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
			MaterialGroupSyncThread thread = new MaterialGroupSyncThread(3,null,Func.toLongList(ids));
			cachedThreadPool.execute(thread);
		}*/
		/**异步向物流推送材料组信息-新增 end**/
		return R.status(flag);
	}
	@GetMapping("/getTree")
	//@ApiOperationSupport(order = 7)
	@ApiOperation(value = "字典树", notes = "传入code,dictKey,childKey")
	public R<List<DictTreeNode>> getTree(String code,String dictKey,String childKey){
		return R.data(materialGroupService.getTree(code,dictKey,childKey));
	}

	/**
	 * 根据物料类型获取物料组信息
	 * @param materialType
	 * @return
	 */
	@GetMapping("/getMaterialGroup")
	@ApiOperation(value = "根据物料类型获取物料组信息")
	public R getMaterialGroup(String materialFlag,String materialType){
		return materialGroupService.getMaterialGroup(materialFlag,materialType);
	}

}

